package com.weetop.cfw.mine.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Html
import android.view.Gravity
import android.view.View
import android.webkit.WebView
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.blankj.utilcode.util.*
import com.gyf.immersionbar.ImmersionBar
import com.kongzue.dialog.v3.MessageDialog
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.anim.DefaultAnimator
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.enums.SidePattern
import com.lzf.easyfloat.interfaces.OnInvokeView
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.weetop.cfw.R
import com.weetop.cfw.application.CFWApplication
import com.weetop.cfw.base.presenter.imp.CourseDetailPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.view.CourseDetailView
import com.weetop.cfw.bean.AudioVideoDetailBean
import com.weetop.cfw.bean.CourseBuyStatus
import com.weetop.cfw.bean.OrderInfoBean
import com.weetop.cfw.bean.RecommendAudioVideoBean
import com.weetop.cfw.callback.RxJavaCallBack
import com.weetop.cfw.constants.UrlConstants
import com.weetop.cfw.mine.adapter.CourseDetailAdapter
import com.weetop.cfw.utils.GlideUtils
import com.weetop.cfw.utils.RetrofitUtils
import com.weetop.cfw.utils.RxJavaUtils
import com.weetop.cfw.utils.WebViewSettingUtils
import kotlinx.android.synthetic.main.activity_course_detail.*


/**
 * 课程详情界面
 */
class CourseDetailActivity : CommonBaseActivity(), View.OnClickListener, CourseDetailView {

    private lateinit var courseDetailAdapter: CourseDetailAdapter

    private lateinit var courseDetailHeaderView: View
    private lateinit var textCourseDetailTitle: TextView
    private lateinit var textCourseDetailAuthorName: TextView
    private lateinit var textCoursePlayNumber: TextView
    private lateinit var courseDescWebView: WebView
    private lateinit var textCourseEpisodeNumber: TextView
    private lateinit var linearCourseDetailContainer: LinearLayout

    private val audioVideoDetailList = ArrayList<AudioVideoDetailBean.DataBean>()

    private lateinit var courseDetailEasyFloatBuilder: EasyFloat.Builder

    private lateinit var floatVideoPlayer: StandardGSYVideoPlayer

    private lateinit var courseDetailPresenterImp: CourseDetailPresenterImp

    private var coverImageUrl: String = ""//视频封面图片链接
    private var videoUrl: String = ""//视频地址

    private var infoId: Int = 0//视频ID
    private var classId: Int = 0//意向ID

    override fun getLayoutId() = R.layout.activity_course_detail

    companion object {
        //视频播放进度
//        var CURRENT_POSITION = "CURRENT_POSITION"
        private const val VIDEO_ID = "VIDEO_ID"
        private const val CLASS_ID = "CLASS_ID"
        private const val VIDEO_URL = "VIDEO_URL"

        fun startCourseDetailActivity(
            context: Context,
            videoId: Int,
            classId: Int,
            videoUrl: String
        ) {
            val intent = Intent(context, CourseDetailActivity::class.java)
            intent.putExtra(VIDEO_ID, videoId)
            intent.putExtra(CLASS_ID, classId)
            intent.putExtra(VIDEO_URL, videoUrl)
            ActivityUtils.startActivity(intent)
        }

        fun startCourseDetailActivity(context: Context, videoId: Int, classId: Int) {
            val intent = Intent(context, CourseDetailActivity::class.java)
            intent.putExtra(VIDEO_ID, videoId)
            intent.putExtra(CLASS_ID, classId)
            ActivityUtils.startActivity(intent)
        }

    }

    override fun initView(savedInstanceState: Bundle?) {
        courseDetailHeaderView = View.inflate(this, R.layout.layout_course_detail_header, null)
        textCourseDetailTitle = courseDetailHeaderView.findViewById(R.id.textCourseDetailTitle)
        textCourseDetailAuthorName =
            courseDetailHeaderView.findViewById(R.id.textCourseDetailAuthorName)
        textCoursePlayNumber = courseDetailHeaderView.findViewById(R.id.textCoursePlayNumber)
        courseDescWebView = courseDetailHeaderView.findViewById(R.id.courseDescWebView)
        textCourseEpisodeNumber = courseDetailHeaderView.findViewById(R.id.textCourseEpisodeNumber)
        linearCourseDetailContainer =
            courseDetailHeaderView.findViewById(R.id.linearCourseDetailContainer)

        ImmersionBar.with(this).transparentStatusBar().fitsSystemWindows(false)
            .statusBarDarkFont(false).init()

        WebViewSettingUtils.initWebView(courseDescWebView)

        courseDetailPresenterImp = CourseDetailPresenterImp()
        courseDetailPresenterImp.attachView(this)

        setViewsOnClickListener(
            this,
            imageCourseDetailBack,
            textCourseDetailBack,
            relativeAtOnceBuyContainer
        )

    }

    //价格为0 状态为已购买  不为0判断购买状态
    var buyStatus: Boolean = false

    /**
     * 视频购买状态
     */
    private fun getCourseStatus(infoid: Int) {
        RxJavaUtils.useInAppCompatActivityOnDestory(
            RetrofitUtils.getApi().getCourseDetailStatus(
                infoid
            ), this, object :
                RxJavaCallBack<CourseBuyStatus>() {
                override fun onSuccess(t: CourseBuyStatus?) {
                    LogUtils.eTag("getCourseStatus", t?.state)
                    if (t?.state == 1) {
                        buyStatus = true
                        relativeVideoPlayerPlaceContainer.visibility = View.GONE
                        relativeAtOnceBuyContainer.setBackgroundResource(R.color.third_text_color)
                        tvBuyText.text = "已购买"
                        relativeAtOnceBuyContainer.isClickable = false
                    } else {
                        buyStatus = false
                        relativeVideoPlayerPlaceContainer.visibility = View.VISIBLE
                        relativeAtOnceBuyContainer.setBackgroundResource(R.color.FF552E)
                        relativeAtOnceBuyContainer.isClickable = true
                        tvBuyText.text = "立即购买"
                    }
                }

                override fun onErrorResponse(throwable: Throwable?) {
                    super.onErrorResponse(throwable)
                }

                override fun onRequestError(t: CourseBuyStatus?) {
                    super.onRequestError(t)
                }

            })
    }


    /**
     * 初始化悬浮窗
     */
    private fun initFloatingWindow() {
        EasyFloat.dismissAppFloat(applicationContext)

        courseDetailEasyFloatBuilder = EasyFloat.with(this)
            .setLayout(R.layout.layout_floating_video, OnInvokeView {

                CFWApplication.isFloatingWindowFirstHide = true
                CFWApplication.videoCurrentProgress =
                    courseDetailVideoPlayer.currentPositionWhenPlaying
                LogUtils.eTag(
                    "courseDetailVideoPlayer.currentPositionWhenPlaying",
                    courseDetailVideoPlayer.currentPositionWhenPlaying,
                    CFWApplication.videoCurrentProgress
                )

                floatVideoPlayer = it.findViewById(R.id.floatVideoPlayer)
                floatVideoPlayer.backButton.visibility = View.GONE
                floatVideoPlayer.setUp(videoUrl, true, "")
                val thumbImageView = ImageView(applicationContext)
                thumbImageView.scaleType = ImageView.ScaleType.CENTER_CROP
                GlideUtils.loadImage(thumbImageView, coverImageUrl, thumbImageView)
                floatVideoPlayer.thumbImageView = thumbImageView
                floatVideoPlayer.isRotateViewAuto = true
                floatVideoPlayer.setIsTouchWiget(true)
                floatVideoPlayer.isAutoFullWithSize = true

                floatVideoPlayer.fullscreenButton.setOnClickListener {
                    startCourseDetailActivity(this@CourseDetailActivity, infoId, 0)
                    EasyFloat.dismissAppFloat(applicationContext)
                }

                val imageCloseFloatWindow = it.findViewById<ImageView>(R.id.imageCloseFloatWindow)
                imageCloseFloatWindow.setOnClickListener {
                    EasyFloat.dismissAppFloat(applicationContext)
                    CFWApplication.videoCurrentProgress = 0
                    GSYVideoManager.releaseAllVideos()
                }
            })
            // 设置浮窗显示类型，默认只在当前Activity显示，可选一直显示、仅前台显示
            .setShowPattern(ShowPattern.FOREGROUND)
            .setSidePattern(SidePattern.RESULT_SIDE)
            .setGravity(Gravity.TOP or Gravity.END, -15, 100)
            .setFilter(CourseDetailActivity::class.java, AudioDetailActivity::class.java)
            // 设置Activity浮窗的出入动画，可自定义，实现相应接口即可（策略模式），无需动画直接设置为null
            .setAnimator(DefaultAnimator())
            // 浮窗的一些状态回调，如：创建结果、显示、隐藏、销毁、touchEvent、拖拽过程、拖拽结束
            // ps：通过Kotlin DSL实现的回调，可以按需复写方法，用到哪个写哪个
            .registerCallback {
                createResult { isCreated, msg, view ->
                }
                show {
                    LogUtils.eTag("EasyFloat", "视频悬浮窗show()")
                    CFWApplication.videoCurrentProgress =
                        floatVideoPlayer.currentPositionWhenPlaying
                    floatVideoPlayer.seekOnStart = CFWApplication.videoCurrentProgress.toLong()
                    floatVideoPlayer.startPlayLogic()
                }
                hide {
                    LogUtils.eTag("EasyFloat", "视频悬浮窗hide()")
                    if (!CFWApplication.isFloatingWindowFirstHide) {
                        CFWApplication.videoCurrentProgress =
                            floatVideoPlayer.currentPositionWhenPlaying
                    }
                    CFWApplication.isFloatingWindowFirstHide = false
                    LogUtils.eTag(
                        "CFWApplication.videoCurrentProgress",
                        CFWApplication.videoCurrentProgress
                    )
                }
                dismiss {
                    LogUtils.eTag("EasyFloat", "视频悬浮窗dismiss()")
                }
                touchEvent { _, _ -> }
                drag { _, _ -> }
                dragEnd { }
            }
    }

    override fun initData(savedInstanceState: Bundle?) {

        infoId = intent.getIntExtra(VIDEO_ID, 0)
        classId = intent.getIntExtra(CLASS_ID, 0)

        btnAtOnceBuy.setOnClickListener {
            courseDetailPresenterImp.getOrderId(this, infoId)
        }

        courseDetailPresenterImp.uploadUserAudioAndVideoBrowsingRecords(this, infoId.toString())

        courseDetailAdapter =
            CourseDetailAdapter(R.layout.layout_course_detail_item, audioVideoDetailList)
        courseDetailAdapter.setOnItemClickListener { _, _, position ->

            if (buyStatus) {
                initStandardGSYVideoPlayer(audioVideoDetailList[position].vfurl)
                var id = audioVideoDetailList[position].tfid
                for (dataBean in audioVideoDetailList) {
                    dataBean.isPlaying = dataBean.tfid == id
                }
                courseDetailAdapter.notifyDataSetChanged()
                courseDetailVideoPlayer.startPlayLogic()
            } else {
                ToastUtils.showShort("该视频还未购买")
            }
        }
        courseDetailAdapter.setHeaderView(courseDetailHeaderView)
        courseDetailRV.adapter = courseDetailAdapter
//       initFloatingWindow()
    }


    override fun onPause() {
        super.onPause()
        courseDetailVideoPlayer.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        courseDetailVideoPlayer.onVideoResume()
        courseDetailPresenterImp.getCourseDetail(this, infoId)
    }

    override fun onDestroy() {
        super.onDestroy()
        courseDetailVideoPlayer.release()
        WebViewSettingUtils.destoryWebView(courseDescWebView, linearCourseDetailContainer)
        courseDetailPresenterImp.detachView()
    }

    override fun onBackPressed() { //先返回正常状态
        //释放所有
        courseDetailVideoPlayer.setVideoAllCallBack(null)
        super.onBackPressed()
    }

    /**
     * 结束该界面并且打开悬浮窗
     */
    private fun finishActivityAndOpenFloatingWindow() {
        if (PermissionUtils.isGrantedDrawOverlays()) {//有悬浮窗权限
            courseDetailEasyFloatBuilder.show()
            ActivityUtils.finishActivity(this@CourseDetailActivity)
        } else {//没有悬浮窗权限
            MessageDialog.show(
                this@CourseDetailActivity,
                "提示",
                "只有开启悬浮窗权限才能使用小窗视频播放，是否前往开启悬浮窗权限？",
                "去开启",
                "暂不开启"
            ).setOnOkButtonClickListener { _, _ ->
                //请求悬浮窗权限
                PermissionUtils.requestDrawOverlays(object : PermissionUtils.SimpleCallback {
                    override fun onGranted() {
                        courseDetailEasyFloatBuilder.show()
                        ActivityUtils.finishActivity(this@CourseDetailActivity)
                    }

                    override fun onDenied() {
                        ToastUtils.showLong("悬浮窗权限已拒绝，无法进行小窗播放视频")
                    }
                })
                true
            }.setOnCancelButtonClickListener { _, _ ->
                ActivityUtils.finishActivity(this@CourseDetailActivity)
                true
            }
        }

    }

//    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        if(keyCode == KeyEvent.KEYCODE_BACK){
//            finishActivityAndOpenFloatingWindow()
//            return true
//        }
//        return super.onKeyDown(keyCode, event)
//    }
    /**
     * 初始化视频播放器
     */
    private fun initStandardGSYVideoPlayer(videoUrl: String) {
        this@CourseDetailActivity.videoUrl = "${UrlConstants.baseUrl}Upload/File/${videoUrl}"
        courseDetailVideoPlayer.setUp(this@CourseDetailActivity.videoUrl, true, "")
        val thumbImageView = ImageView(this)
        thumbImageView.scaleType = ImageView.ScaleType.CENTER_CROP
        GlideUtils.loadImage(thumbImageView, coverImageUrl, thumbImageView)
        courseDetailVideoPlayer.thumbImageView = thumbImageView
        courseDetailVideoPlayer.isRotateViewAuto = true
        courseDetailVideoPlayer.setIsTouchWiget(true)
        courseDetailVideoPlayer.isAutoFullWithSize = true
        courseDetailVideoPlayer.isShowFullAnimation = true


        courseDetailVideoPlayer.fullscreenButton.setOnClickListener {
            courseDetailVideoPlayer.startWindowFullscreen(this@CourseDetailActivity, false, true)
        }

        if (CFWApplication.videoCurrentProgress > 0) {
            courseDetailVideoPlayer.seekOnStart = CFWApplication.videoCurrentProgress.toLong()
            courseDetailVideoPlayer.startPlayLogic()
            CFWApplication.videoCurrentProgress = 0
        }

    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.imageCourseDetailBack, R.id.textCourseDetailBack -> finish()
            R.id.relativeAtOnceBuyContainer -> courseDetailPresenterImp.getOrderId(this, infoId)
        }
    }

    /**
     * 商业云课详情获取成功
     */
    override fun courseDetailDataGetSuccess(audioVideoDetailBean: AudioVideoDetailBean?) {
        if (audioVideoDetailBean != null) {
            courseDetailVideoPlayer.backButton.visibility = View.GONE
            textCourseDetailTitle.text = audioVideoDetailBean.title
            coverImageUrl = "${UrlConstants.baseUrl}${audioVideoDetailBean.imgurl}"
            textCourseDetailAuthorName.text = audioVideoDetailBean.author
            textCoursePlayNumber.text = "${audioVideoDetailBean.playnum}次播放"
            courseDescWebView.loadData(
                Html.fromHtml(audioVideoDetailBean.content).toString(),
                "text/html; charset=UTF-8",
                null
            )
            textCourseEpisodeNumber.text = "共${audioVideoDetailBean.data.size}集"
            SpanUtils.with(textCoursePrice).append("￥${audioVideoDetailBean.sprice}")
                .setForegroundColor(ColorUtils.getColor(R.color.FF552E)).setBold()
                .append("￥${audioVideoDetailBean.mprice}")
                .setForegroundColor(ColorUtils.getColor(R.color.secondary_text_color))
                .setStrikethrough().create()

            audioVideoDetailList.addAll(audioVideoDetailBean.data)
            courseDetailAdapter.notifyDataSetChanged()

            if (audioVideoDetailList.size > 0) {
                audioVideoDetailList[0].isPlaying = true
                courseDetailAdapter.notifyDataSetChanged()
                initStandardGSYVideoPlayer(audioVideoDetailList[0].vfurl)
            }
            if (audioVideoDetailBean.sprice == null || audioVideoDetailBean.sprice.toDouble() == 0.0) {
                buyStatus = true
                relativeVideoPlayerPlaceContainer.visibility = View.GONE
                relativeAtOnceBuyContainer.setBackgroundResource(R.color.third_text_color)
                tvBuyText.text = "已购买"
                relativeAtOnceBuyContainer.isClickable = false
            } else {
                buyStatus = false
                relativeVideoPlayerPlaceContainer.visibility = View.VISIBLE
                relativeAtOnceBuyContainer.setBackgroundResource(R.color.FF552E)
                relativeAtOnceBuyContainer.isClickable = true
                tvBuyText.text = "立即购买"
                getCourseStatus(infoId)
            }
        }
    }

    /**
     * 推荐视频获取成功
     */
    override fun getRecommendVideoSuccess(recommendAudioVideoBean: RecommendAudioVideoBean?) {
        if (recommendAudioVideoBean != null) {

        }
    }

    /**
     * 订单ID获取成功
     */
    override fun getOrderIdSuccess(orderId: String) {
//         courseDetailPresenterImp.getOrderInfo(this,orderId)
        ConfirmationOfOrderActivity.startConfirmationOfOrderActivity(this, orderId, infoId)
    }

    /**
     * 订单信息获取成功
     */
    override fun orderInfoGetSuccess(orderInfoBean: OrderInfoBean) {

    }

}
